//
//  HomeViewController.swift
//  DaRings
//
//  Created by 尹琼 on 2022/10/27.
//

import UIKit
import MYModule
import RxDataSources
import RxSwift
import RxCocoa
import RxViewController
import MJRefresh
import EachNavigationBar
import CRPSmartRing

open class HomeViewController: ViewController {
    

    let tableView: TableView = TableView(frame: CGRect.zero, style: .plain)
    
    var viewModel: HomeViewModel?
    
    let headerView = HomeTableHeaderView()
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        
        BluetoothResponder.shared.delegate = self
        
        self.adjustsConfig()
        
        
        
    }
    
    
    func adjustsConfig() {
        
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
    }
    
    func navigationBarUI() {
        
        let leftLabel = Label()
        
        leftLabel.textColor = UIColor.assist_222222
        leftLabel.font = Fonts.boldSystemFont(ofSize: 24)
        leftLabel.text = "today".language
        
        self.navigation.item.leftBarButtonItem = UIBarButtonItem(customView: leftLabel)
        
    }
    
    var cellTypeClasses: [HomeBaseCell.Type] {
        
        return HomeCellType.allCases.map({ self.cellClass(with: $0) })
    }
    
    func cellClass(with cellType: HomeCellType) -> HomeBaseCell.Type {
        
        switch cellType {
        case .device:
            return HomeDeviceCell.self
        case .activity:
            return HomeActivityCell.self
        case .sleep:
            return HomeSleepCell.self
        case .stress:
            return HomeStressCell.self
        case .bloodOxygen:
            return HomeBloodOxygenCell.self
        case .hrv:
            return HomeHRVCell.self
        case .workoutsRecords:
            return HomeWorkoutsRecordsCell.self
        case .heartRate:
            return HomeHeartRateCell.self
        }
    }
    
    
   public override func makeUI() {
        super.makeUI()
       
       navigationBarUI()
       
       self.view.backgroundColor = UIColor.background
       
       // 下拉刷新
       let mjHeader = MJRefreshNormalHeader {[weak self] in
           
           DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) {
               self?.tableView.mj_header?.endRefreshing()
           }
       }
       mjHeader.stateLabel?.isHidden = true
       tableView.mj_header = mjHeader
       
       tableView.showsVerticalScrollIndicator = false
       
       for cellTypeClass in self.cellTypeClasses {
           tableView.register(cellTypeClass, forCellReuseIdentifier: cellTypeClass.reuseIdentifier)
       }
       
       view.addSubview(tableView)

       tableView.snp.makeConstraints { make in
           
           make.top.equalTo(UIApplication.shared.statusBarFrame.height)
           
           make.left.right.equalToSuperview()
           if #available(iOS 11.0, *) {
               
               make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
           } else {
               
               guard let tabBar = self.tabBarController?.tabBar else {
                   return
               }
               
               make.bottom.equalTo(tabBar.snp.top)
           }
       }
       
       guard let navigationBar = self.navigationController?.navigationBar else { return }
       
       tableView.tableHeaderView = headerView
       
      
       var top: CGFloat = 20.0
       
       if #available(iOS 11.0, *) {
           top = UIApplication.shared.keyWindow?.safeAreaInsets.top ?? 64.0
       } else {
           top = UIApplication.shared.statusBarFrame.height
       }
      
       top = top + navigationBar.frame.maxY
       
       tableView.rx.contentOffset.map { CGFloat($0.y/top) }.subscribe(onNext: {[weak self] in
           
           
           self?.navigation.bar.alpha = $0
           
           self?.headerView.titleLabel.isHidden = $0 > 0.1
           self?.headerView.dateLabel.isHidden = $0 > 0.1
           
           self?.navigation.item.leftBarButtonItem?.customView?.alpha = $0
           
       }).disposed(by: rx.disposeBag)
       
    }

    open override func bindViewModel() {
        super.bindViewModel()
        
        let input = HomeViewModel.Input(viewWillAppear: self.rx.viewWillAppear, headerRefresh: tableView.mj_header?.rx.refresh)
        
        let viewModel = HomeViewModel(input: input)
        
        let output = viewModel.transform(input: input)
        
        output.dateObserver.subscribe(onNext: {[weak self] in
            
            self?.headerView.date = $0
            
        }).disposed(by: rx.disposeBag)
        
       
        self.viewModel = viewModel
        
        guard let output = self.viewModel?.outPut else { return }
        
        let datasource = RxTableViewSectionedReloadDataSource<HomeSection> {[weak self] dasource, tableView, indexPath, item in
            
            guard let self = self else { return UITableViewCell() }
            
            let indentifier = self.cellClass(with: item.cellType).reuseIdentifier
            let cell = tableView.dequeueReusableCell(withIdentifier: indentifier, for: indexPath) as! HomeBaseCell
            
            cell.bind(to: item)
            
            if cell is HomeWorkoutsRecordsCell {
                
                let cell = cell as? HomeWorkoutsRecordsCell
                cell?.tapHandle = {[weak self] in
                    
                    self?.pushToTrainningTypeController()
                }
            }
            
            cell.selectedItem = {[weak self] in
                self?.selectedItem(viewModel: item)
            }
            
            return cell
        }
        
        
        output.dataSource.bind(to: tableView.rx.items(dataSource: datasource)).disposed(by: rx.disposeBag)
        
        
    }
    
    
    open override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        headerView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
        }
        
        headerView.layoutIfNeeded()
        tableView.reloadData()
    }
    
}

extension HomeViewController {
    
    func selectedItem(viewModel: HomeBaseViewModel) {
        
        let cellType = viewModel.cellType

        switch cellType {

        case .device:
           pushToADeviceController()
            break
        case .activity:
            pushToActivityShortController()
            break
        case .sleep:
            pushToSleepShortController()
            break
        case .bloodOxygen:
            pushToBloodOxygenController()
            break
        case .hrv:
            pushToHRVController()
            break
        case .stress:
            pushToStressController()
            break
        case .workoutsRecords:

            pushToTrainingRecordListController()
            break
        case .heartRate:
            pushToHeartRateController()
            break
        }
    }
    
}

extension HomeViewController {
    
    func pushToADeviceController() {
        
        let vc = BindingController()
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToSleepShortController() {
        
        let vc = SleepViewController()
        vc.revealAll = false
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    func pushToActivityShortController() {
        
        let vc = ActivityHomeController()
        vc.revealAll = false
        self.navigationController?.pushViewController(vc, animated: true)

        
    }
    
    func pushToTrainingRecordListController() {
        
        let vc = TrainingRecordsController()
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToTrainningTypeController() {
        
        let vc = TrainingTypeListController()
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
    func pushToHeartRateController() {
        
//        let vc = SingleHeartRateDetailController()
        
        let vc = HeartRateDetailController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func pushToBloodOxygenController() {
        
        let vc = BloodOxygenDetailController()
        vc.provider = BloodOxygenProvider(date: viewModel?.outPut.bloodOxygen.value?.date)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func pushToHRVController() {
        
        let vc = HRVDetailController()
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func pushToStressController() {
        let vc = StressDetailViewController()
        vc.provider = StressProvider(date: viewModel?.outPut.stress.value?.date)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    

}


extension HomeViewController: BluetoothResponderDelegate {
    
    
    /// 是否在当前控制器弹窗强制升级弹窗
    /// - Parameters:
    ///   - responder: responder
    ///   - atCurrentViewController: 当前控制器
    public func shoudShowUpgradeAlert(responder: BluetoothResponder, atCurrentViewController: UIViewController) ->Bool {
        
       return !(atCurrentViewController is FirmwareUpgradeController)
    }
    
    /// 去固件升级页面
    /// - Parameters:
    ///   - responder: responder
    ///   - provider: ota info
    ///   - fileInfo: file info
    /// - Returns: 控制器
    public func willPushToUpgradeController(responder: BluetoothResponder, provider: OTAProvider, fileInfo: OTAProvider.FileInfo) ->UIViewController {
        
        let upgradeVC = FirmwareUpgradeController()
        upgradeVC.otaType = fileInfo.type
        upgradeVC.fileInfo = fileInfo
        
        return upgradeVC
        
    }
    
    
    /// 即将去正在锻炼中的锻炼页面
    /// - Parameters:
    ///   - responder: responder
    ///   - trainModel: model
    public func willPushToTrainingController(responder: BluetoothResponder, trainModel: TrainingModel) {
        
        guard let trainingType = TrainingType(rawValue: trainModel.type), let currentVC = UIViewController.currentViewController() else { return }
        
        if currentVC is GPSTrainingMapViewController {
            guard let vc = currentVC as? GPSTrainingMapViewController else { return }
            vc.reloadTrainingModel()
            return
        }
        
        if currentVC is InTrainingController {
            guard let vc = currentVC as? InTrainingController else { return }
            vc.reloadTrainingModel()
            return
        }
        

        if trainingType.isGPS {
            
            let vc = GPSTrainingMapViewController()
            let route = trainModel
            vc.type = trainingType
            if let goalType = CRPTrainingGoalType(rawValue: trainModel.goalType)?.trainingContentType {
                vc.gpsGoal(type: goalType, goal: Double(trainModel.goal))
            }
            // 运动时长(因为是再次进入锻炼中，所以trainModel.vaildTime一定有值，因为他是运动中的时候定时器每秒存一次的)
            vc.runTime = trainModel.vaildTime
            vc.gpsTrainModel = route
            
            let currentVC = UIViewController.currentViewController()
            currentVC?.navigationController?.pushViewController(vc, animated: true)
            
        } else {
            
            let vc = InTrainingController()
            vc.type = trainingType
            if let goalType = CRPTrainingGoalType(rawValue: trainModel.goalType)?.trainingContentType  {
                vc.goalType = goalType
            }
            vc.startTime = trainModel.startTime
            vc.time_second = trainModel.vaildTime
            
            let currentVC = UIViewController.currentViewController()
            currentVC?.navigationController?.pushViewController(vc, animated: true)
            
        }
        
    }
    
    
    public func trainingIsEnd(responder: BluetoothResponder, trainModel: TrainingModel?) {
        
        guard let currentVC = UIViewController.currentViewController() else { return }
        
        if currentVC is GPSTrainingMapViewController {
            guard let vc = currentVC as? GPSTrainingMapViewController else { return }
            vc.reloadTrainingModel()
            return
        }
        
        if currentVC is InTrainingController {
            guard let vc = currentVC as? InTrainingController else { return }
            vc.reloadTrainingModel()
            return
        }
        
    }
    
    
}










